package com.warmlight.voicepacket.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.adapter.comm.FocusAdapter;
import com.warmlight.voicepacket.base.activity.BaseActivity;
import com.warmlight.voicepacket.bean.comm.CommBean;
import com.warmlight.voicepacket.bean.comm.CommList;
import com.warmlight.voicepacket.contract.TopicContract;
import com.warmlight.voicepacket.loadmore.HeaderAndFooterRecyclerViewAdapter;
import com.warmlight.voicepacket.network.MapComm;
import com.warmlight.voicepacket.plugin.QmzbMediaManager;
import com.warmlight.voicepacket.plugin.QmzbVideoPlayer;
import com.warmlight.voicepacket.presenter.TopicPresenter;
import com.warmlight.voicepacket.ui.communitylm.widget.CommunityShare;
import com.warmlight.voicepacket.utils.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by weiweijinpeng on 2018/9/17.
 * 话题
 */

public class CommTopicActivity extends BaseActivity implements View.OnClickListener,TopicContract.View,FocusAdapter.FocusItemListener{

    public static void startCommTopicActivity(Context context, String itemId){
        Intent intent=new Intent(context,CommTopicActivity.class);
        intent.putExtra("itemId",itemId);
        context.startActivity(intent);
    }

    TopicContract.Presenter mPresenter;

    List<CommList> mData=new ArrayList<>();

    CommList commList;

//    @BindView(R.id.recycler_view)
//    LoadRecyclerView mRecyclerView;

//    @BindView(R.id.app_myAuto)
//    AutoSwipeRefreshLayout mAuto;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout smartRefreshLayout;

    @BindView(R.id.comment_rl)
    RecyclerView mRecyclerView;

    @BindView(R.id.loading_progress)
    ProgressBar mLoadingBar;

    @BindView(R.id.showdraw)
    ImageView mShowDraw;

    @BindView(R.id.topicTitle)
    TextView mTopicTitle;

    @BindView(R.id.topicCount)
    TextView mTopicCount;

    LinearLayoutManager linearLayoutManager;

    FocusAdapter.FocusRecommViewHolder centerHolder;

    FocusAdapter.FocusRecommNormalViewHolder centerNormalHolder;

    FocusAdapter.FocusPictureViewHolder pictureHolder;

    FocusAdapter focusAdapter;

    PlayHandler playHandler;

    int currentPosition=0;

    int likePosition;

    int page=1;

    int pageSize = 8;

    private int type=0;//0　刷新  1加载

    String mType;

    private int isLike;

    int likeCommPosition;

    private int isCommLike;

    String typeClick;//点赞的类型

    // 标志位，标志已经初始化完成。
    private boolean isPrepared;

    private boolean liveVideo;

    boolean onResumeoFist=false;//判断是否第一进入onResum，如果第二次直接播放上次跳走的位置视频


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commtopic);

        getStatusBarId();
        onImmersionStatusBar();
        initViews();
        setData(true);
    }

    @Override
    public int getStatusBarId() {
        return R.id.status_padding;
    }

    private void  initViews(){
        playHandler=new PlayHandler();

//        mAuto.setOnRefreshListener(this);
//        mRecyclerView.setLoadListener(this);

        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                setData(false);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                setData(true);
            }
        });

        focusAdapter = new FocusAdapter(this,this,getIntent().getStringExtra("itemId"));
//        mRecyclerView.setIsHaveData(false);

        linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);

        //自定义加载布局
        HeaderAndFooterRecyclerViewAdapter customAdapter = new HeaderAndFooterRecyclerViewAdapter(focusAdapter);

        mRecyclerView.setAdapter(customAdapter);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        playVideo();

                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                        stopVideo();
                        break;
                    default:
                        break;
                }
            }
        });
    }

    public void setData(boolean isRefresh){

        startRefresh();

        if (isRefresh){
            page = 1;
        }else{
            page ++;
        }

        MapComm mapComm=new MapComm();
        mapComm.put("page", String.valueOf(page));
        mapComm.put("pagesize",String.valueOf(pageSize));
        mapComm.put("topic_id",getIntent().getStringExtra("itemId"));
        getPresenter().getTopicList(MapComm.getMap());
    }

    @Override
    public TopicContract.Presenter getPresenter() {
        if (mPresenter==null){
            mPresenter=new TopicPresenter(this,this);
        }
        return mPresenter;
    }

    @Override
    public void setPresenter(TopicContract.Presenter presenter) {

    }

    @Override
    public void onTopicList(CommBean list) {
        mTopicTitle.setText(list.getTopic().getTitle());
        mTopicCount.setText("数量"+list.getTopic().getPost_num());

        if (list.getHas_more().equals("0") || list.getHas_more().equals("false")){
            smartRefreshLayout.setNoMoreData(true);
        }else{
            smartRefreshLayout.setNoMoreData(false);
        }

        stopRefresh();
        mData.addAll(list.getList());
        if (page==1){
            if (list.getList().size() == 0){
                smartRefreshLayout.setNoMoreData(true);
            }
            focusAdapter.setData(list.getList());
            playMedia();
        }else {
            if (list.getList().size() == 0){
                smartRefreshLayout.setNoMoreData(true);
            }
            focusAdapter.addData(list.getList());
        }

        smartRefreshLayout.finishRefresh();

        smartRefreshLayout.finishLoadMore();
    }

    private void playMedia(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Message message=new Message();
                message.what=0;
                playHandler.handleMessage(message);
            }
        },200);
    }


    /**
     * 播放视频
     */
    private void playVideo(){

        if (currentPosition == playVideoss()){
            return;
        }

        playVideo(playVideoss());

    }

    /**
     * 滑动或者holder是图片暂停播放
     */
    private void stopVideo(){
        try {
            if (liveVideo)
                QmzbMediaManager.pause();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 播放视频
     */
    private void playVideo(int firstPosition) {

        Log.e("可见区域最大值"+firstPosition);

        currentPosition = firstPosition;

        //视频页
        if (mData.size() > currentPosition && mData.size() != 0)
            commList = mData.get(currentPosition);
        View childAt = linearLayoutManager.findViewByPosition(currentPosition);

        if (childAt !=null)

            if (commList.getPics().size()==0){
                liveVideo=true;
                focusAdapter.videoPreppare(childAt,currentPosition);

            }else{
                stopVideo();
            }
    }

    @OnClick({R.id.showdraw,R.id.loading_progress})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.showdraw:
                finish();
                break;
            case R.id.loading_progress:
                setData(true);
                break;
        }
    }

    private class PlayHandler extends Handler{

        @Override
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    playVideo(0);
                    break;
            }
        }
    }

    @Override
    public void isLikeClick(int position,String type,String clickType) {
        typeClick=clickType;
        likePosition=position;
        mType=type;
        isLike=mData.get(position).getIs_like();
        int count= isLike==0 ? 1 : 2;

        MapComm mapComm=new MapComm();
        mapComm.put("id",mData.get(position).getId());
        mapComm.put("type","1");
        mapComm.put("status",String.valueOf(count));
        getPresenter().getLikeList(MapComm.getMap());

    }

    @Override
    public void isLikeCommClick(int position, String type,String clickType) {
        typeClick=clickType;
        likeCommPosition=position;
        mType=type;
        isCommLike=mData.get(position).getGod_info().getIs_like();
        int count= isCommLike==0 ? 1 : 2;

        MapComm mapComm=new MapComm();
        mapComm.put("id",mData.get(position).getGod_info().getId());
        mapComm.put("type","2");
        mapComm.put("status",String.valueOf(count));
        getPresenter().getLikeList(MapComm.getMap());

    }

    @Override
    public void onLikeList(String list) {
        if (list.toString().equals("成功")){

            if (typeClick.equals("comm")){
                commLike();
                return;
            }

            isLike=isLike==0 ? 1 : 0;

            int count= isLike==0 ? -1 : 1;

            String like_num = focusAdapter.getData().get(likePosition).getLike_num();
            if (!like_num.contains("w") && !like_num.contains("k")){
                int resetCount=Integer.valueOf(focusAdapter.getData().get(likePosition).getLike_num());

                focusAdapter.getData().get(likePosition).setLike_num(String.valueOf(resetCount+count));
            }

            focusAdapter.getData().get(likePosition).setIs_like(isLike);

            focusAdapter.isLike(likePosition);
        }
    }

    /**
     * 神评点赞
     */
    private void commLike(){
        commList = mData.get(likeCommPosition);

        isCommLike = isCommLike==0 ? 1 : 0;

        int count= isCommLike==0 ? -1 : 1;

        String like_num = focusAdapter.getData().get(likeCommPosition).getGod_info().getLike_num();
        if (!like_num.contains("w") && !like_num.contains("k")){
            int resetCount=Integer.valueOf(focusAdapter.getData().get(likeCommPosition).getGod_info().getLike_num());
            focusAdapter.getData().get(likeCommPosition).getGod_info().setLike_num(String.valueOf(resetCount+count));
        }

        focusAdapter.getData().get(likeCommPosition).getGod_info().setIs_like(isCommLike);

        focusAdapter.isLike(likeCommPosition);
    }


    /**
     * 开始刷新动画
     */
    public void startRefresh() {
        mLoadingBar.setIndeterminateDrawable(getResources().getDrawable(
                R.drawable.sample_footer_loading_progress));
        mLoadingBar.setProgressDrawable(getResources().getDrawable(
                R.drawable.sample_footer_loading_progress));
    }

    /**
     * 停止刷新动画
     */
    public void stopRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mLoadingBar.setIndeterminateDrawable(getResources().getDrawable(
                        R.drawable.refresh));
                mLoadingBar.setProgressDrawable(getResources().getDrawable(
                        R.drawable.refresh));
            }
        },500);
    }

    /**
     * 获取当前viewke可见的索引
     * @return
     */
    public int playVideoss() {
        int firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
        int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
        int currentIndex = firstVisibleItem;
        int lastHeight = 0;
        for (int i = firstVisibleItem; i <= lastVisibleItem; i++) {
            View view = linearLayoutManager.getChildAt(i - firstVisibleItem);
            if (null == view) {
                continue;
            }
            int[] location = new int[2];
            view.getLocationOnScreen(location);
            Rect localRect = new Rect();
            view.getLocalVisibleRect(localRect);
            int showHeight = localRect.bottom - localRect.top;
            if (showHeight > lastHeight) {
                currentIndex = i;
                if (currentIndex < 0) {
                    currentIndex = 0;
                }
                lastHeight = showHeight;
            }
        }
        return currentIndex;
    }


    @Override
    public void shareClick(int position) {
        Map<String,String> map=new HashMap<>();
        map.put("title",mData.get(position).getShare().getTitle());
        map.put("msc",mData.get(position).getShare().getDesc());
        map.put("url",mData.get(position).getShare().getH5_url());
        map.put("img",mData.get(position).getShare().getPic_url());
        map.put("type","1");
        map.put("id",mData.get(position).getId());
        CommunityShare.getInstance(map).show(getSupportFragmentManager().beginTransaction()
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE),"ads");
    }

    @Override
    public void onTopicFailure() {
//        mAuto.setRefreshing(false);
        smartRefreshLayout.autoRefresh();
    }

    @Override
    public void onTopicNoMore() {

    }

    @Override
    public void onNoNetWork() {

    }

    @Override
    protected void onPause() {
        super.onPause();
        onResumeoFist=true;
        QmzbVideoPlayer.onPlayOnPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (onResumeoFist)
            playVideo(playVideoss());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
